package com.example.musicplayer.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.musicplayer.DataLoadManager;
import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.R;
import com.example.musicplayer.commonUtils.StringUtil;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.dialogTools.NormalAlertDialog;

public class TimedOffService extends IntentService {
    private static final String TAG = "TimedOffService";
    //show prompt dialog
    private static final int SHOW_PROMPT_DIALOG = 1;
    //dismiss prompt dialog
    private static final int CLOSE_PROMPT_DIALOG = 2;
    private static final int TIME_INTERVAL = 500;
    //the left time to show a prompt dialog
    private static final int LEFT_TIME_TO_PROMPT = 10 * 1000;
    //if timed off service has been started
    private static boolean sHasStartService = false;
    //if interrupt this service thread
    private static boolean sStopService = false;
    //set as true when set exit style as exit app after current music end
    private static boolean sExitAppFlag = false;
    //time to off app
    private static long sOffTime = 0;
    private TimedOffHandler mHandler;

    private static class TimedOffHandler extends Handler {
        private NormalAlertDialog mPromptDialog;

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_PROMPT_DIALOG:
                    mPromptDialog = MusicPlayerApplication.showTimedOffPromptDialog();
                    break;
                case CLOSE_PROMPT_DIALOG:
                    if (mPromptDialog != null) {
                        mPromptDialog.dismiss();
                        mPromptDialog = null;
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public TimedOffService() {
        super(TAG);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new TimedOffHandler();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler = null;
    }

    public static void startTimedOffService(Context context, int timeDuration) {
        if (timeDuration > 0) {
            showToast(context, timeDuration);
            sOffTime = System.currentTimeMillis() + timeDuration;
            //if has start, do not start again
            if (!sHasStartService) {
                //if start service but not end now
                if (sStopService) {
                    try {
                        Thread.sleep(TIME_INTERVAL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                sHasStartService = true;
                sExitAppFlag = false;
                Intent intent = new Intent(context, TimedOffService.class);
                context.startService(intent);
            }
        }
    }

    public static void stopTimedOffService() {
        if (sHasStartService || sStopService) {
            sHasStartService = false;
            sStopService = true;
        }
        sExitAppFlag = false;
    }

    public static long getOffTime() {
        return sOffTime;
    }

    public static boolean serviceIsStart() {
        return sHasStartService || sExitAppFlag;
    }

    public static boolean getExitAppFlag() {
        return sExitAppFlag;
    }

    public static int getTimeInterval() {
        return TIME_INTERVAL;
    }

    private static void showToast(Context context, int duration) {
        String timePoint = StringUtil.getFormatDate(System.currentTimeMillis() + duration, "HH:mm");
        String text1 = context.getResources().getString(R.string.timing_set_success_1);
        if (!StringUtil.compareTwoDate(timePoint, StringUtil.getFormatDate(System.currentTimeMillis(), "HH:mm"))) {
            text1 = context.getResources().getString(R.string.timing_set_success_1_tomorrow);
        }
        text1 += timePoint;
        text1 += context.getResources().getString(R.string.timing_set_success_2);
        ToastUtil.makeToast(text1);
    }

    private void timingEnd() {
        sHasStartService = false;
        sStopService = false;
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //confirm that thread has been start
        sHasStartService = true;
        boolean showPromptDialog = false;
        long currentTime = System.currentTimeMillis();
        while (currentTime < sOffTime) {
            if (sStopService) {
                stopSelf();
                timingEnd();
                return;
            }
            if (sOffTime - currentTime <= LEFT_TIME_TO_PROMPT && !showPromptDialog) {
                mHandler.sendEmptyMessage(SHOW_PROMPT_DIALOG);
                showPromptDialog = true;
            }
            try {
                Thread.sleep(TIME_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            currentTime = System.currentTimeMillis();
        }
        timingEnd();
        //dismiss the prompt dialog
        mHandler.sendEmptyMessage(CLOSE_PROMPT_DIALOG);
        //get end app style
        DataLoadManager dataLoadManager = DataLoadManager.getInstance();
        boolean exitNow = true;
        if (dataLoadManager != null) {
            exitNow = dataLoadManager.readOneBaseData(DataLoadManager.TIMED_OFF_IMMEDIATE, true);
        }
        if (exitNow) {
            //exit app right now
            MusicPlayerApplication.getInstance().exit();
        } else {
            sExitAppFlag = true;
        }
    }
}